﻿using System;
using System.IO;
using System.Linq;
using System.Drawing.Imaging;
using System.Web.UI;
using WhsFacebook.Net.Web.Database;
using WhsFacebook.Whs;

namespace WhsFacebook.Net.Web.Facebook.Handlers
{
    /// <summary>
    /// see http://msdn.microsoft.com/en-us/library/system.web.httpresponse.outputstream.aspx
    /// </summary>
    public partial class StorageChartJpeg : System.Web.UI.Page
    {
        private readonly log4net.ILog _log = log4net.LogManager.GetLogger(typeof(StorageChartJpeg));

        protected void Page_Load(object sender, EventArgs e)
        {
            // gather instance id
            var id = this.Request.Params["id"];

            if (string.IsNullOrEmpty(id))
                throw new ArgumentException("Missing instance 'id' parameter", "id");

            Guid instanceId;

            if (!Guid.TryParse(id, out instanceId))
                throw new ArgumentException("Failed to parse instance 'id' parameter", "id");

            // already rendered?
            byte[] image;

            using (var db = new WhsFacebookEntities())
            {
                var inst = db.UserStorageInfosLatests.Where(o => o.InstanceId == instanceId).FirstOrDefault();

                if (inst == null)
                {
                    // show error image
                    image = Properties.Resources.binErrorImageNoStorageData_jpg;
                }
                else
                {
                    // has jpeg?
                    var storedJpeg = inst.StorageChartJpeg;

                    if ((storedJpeg != null) && (storedJpeg.Length > 0))
                    {
                        image = storedJpeg;
                    }
                    else
                    {
                        // render the chart
                        EnsureChildControls();

                        // bind simple storage data
                        {
                            var s = this.chart.Series[0];

                            s.Clear();

                            s.AddItem(inst.StorageUsedSpace, WhsFacebookHelpers.GetNiceFileSize(inst.StorageUsedSpace) + " used");
                            s.AddItem(inst.StorageFreeSpace, WhsFacebookHelpers.GetNiceFileSize(inst.StorageFreeSpace) + " free");
                        }

                        // bind detailed storage data
                        {
                            var s = this.chart.Series[1];

                            s.Clear();

                            // aggregate small parts
                            var osNew = (inst.AppFoldersSize + inst.OperatingSystemSize);
                            var newFiles = (inst.SharedFoldersSize + inst.SharedFoldersDupSize);

                            s.AddItem(osNew, WhsFacebookHelpers.GetNiceFileSize(osNew) + " System");
                            s.AddItem(inst.BackupSize, WhsFacebookHelpers.GetNiceFileSize(inst.BackupSize) + " Backups");
                            s.AddItem(newFiles, WhsFacebookHelpers.GetNiceFileSize(newFiles) + " Files");
                            s.AddItem(inst.StorageFreeSpace, WhsFacebookHelpers.GetNiceFileSize(inst.StorageFreeSpace) + " free");
                        }

                        // create image);
                        using (var ms = new MemoryStream())
                        {
                            this.chart.Save(ms, ImageFormat.Jpeg);

                            ms.Flush();

                            image = ms.ToArray();
                        }

                        // save it into the database
                        try
                        {
                            inst.StorageChartJpeg = image;

                            db.SaveChanges();
                        }
                        catch (Exception x)
                        {
                            if (_log.IsWarnEnabled)
                                _log.Warn("Failed to save storage chart to DB", x);
                        }
                    }
                }
            }

            // output the image to the user
            this.Response.Clear();

            this.Response.ContentType = "image/jpeg";

            this.Response.BufferOutput = true;

            this.Response.OutputStream.Write(image, 0, image.Length);

            this.Response.End();
        }

        protected override void Render(HtmlTextWriter writer)
        {
            //base.Render(writer);
        }

        public override void RenderControl(HtmlTextWriter writer)
        {
            //base.RenderControl(writer);
        }

         
    }
}